import { observable, action, computed, toJS } from "mobx";
import { message, Modal } from 'antd';
import { fillinTypes, appStatus, DESIGN_URL } from "../constants/app";
import { WeaForm } from 'comsMobx';
import _action, { shareList, deleteShare } from "../apis/app";
import TASKAPI from '../apis/task';
import route from "../constants/route";
import { createCondition, createDay } from "./task/newTaskCondition";

import { WeaTableNew } from 'comsMobx'
const { TableStore } = WeaTableNew;
import '../components/list/card/index.less'
import { WeaTools, WeaLocaleProvider } from "ecCom";

const { INPUT } = WeaTools.types;
const getLabel = WeaLocaleProvider.getLabel;

const { ALL, FREE, MULTI } = fillinTypes;
const { UNKNOWN, DELETE, EDIT, NEW } = appStatus;

export default class AppManageStore {
  @observable loading = false; // WeaTop loading
  @observable spinning = false; // Spin spinning
  @observable status = UNKNOWN; // 应用操作状态 编辑 删除 新建 
  // @observable apps = []; // 填报的应用
  @observable counts = []; // 应用计数
  @observable selectedType = ALL; // 选中的应用类型
  @observable types = []; // 应用类型
  @observable searchText = ''; // 应用搜索关键字
  @observable editableApp = {}; // 编辑状态的应用
  @observable appids = []; // 选中的应用ids

  @observable newTaskDialogVisible = false;
  @observable newTaskSubmiting = false;
  @observable newTaskApp = {};
  @observable newTaskFrom = new WeaForm();

  @observable publishDialogVisible = false;
  @observable publishApp = {};
  @observable baseDateHide = true;

  // 共享
  @observable shareDialogVisible = false;
  @observable shareListVisible = false;
  @observable shareListType = 'default';
  @observable shareListTableStore = new TableStore();
  @observable shareForm = new WeaForm();
  @observable shareApp = {};


  @observable createRight = false;//新建权限
  @observable modifyRight = false;//维护权限
  @observable canCreated = false;//再创建权限

  //@observable total = 0;
  @observable current = 1;
  @observable pageSize = 20;

  @observable tableStore = new TableStore();
  @observable sessionkey = '';
  @observable selectedGroupType = '-2'; // 选中的分组
  @observable firstGroup = '-1';
  @observable searchValue = ''; // 检索值
  @observable leftDatas = [];
  @observable appGroupFrom = new WeaForm();
  @observable newAppGroupDialogVisible = false;
  @observable newAppGroup = {};
  @observable notMine;

  @computed get newTaskDialog() {
    return {
      visible: this.newTaskDialogVisible,
      app: this.newTaskApp,
      onCancel: this.hideNewTaskDialog,
      submiting: this.newTaskSubmiting,
      form: this.newTaskFrom,
      onSave: this.saveTask,
      showDesigner: this.showDesigner,
    }
  }

  @computed get newAppGroupDialog() {
    return {
      visible: this.newAppGroupDialogVisible,
      app: this.AppGroup,
      onCancel: this.hideNewAppGroupDialog,
      submiting: this.newTaskSubmiting,
      form: this.appGroupFrom,
      onSave: this.saveGroupApp
    }
  }

  @computed get shareDialog() {
    return {
      visible: this.shareDialogVisible,
      onCancel: this.hideShareDialog,
      title: `共享：${this.shareApp.name}`,
      onOk: this.saveShareApp,
    }
  }

  @computed get groupTypes() {
    const types = this.leftDatas.filter(d => (d.groupName.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1) ||
      (d.creator.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1));

      return types;
  }

  @computed get myGroups() {
    return this.leftDatas.map(s => ({key:s.id+'',showname:s.groupName,selected:s.isdefault == '1' }));
  }

  @computed get myGroupTypes() {
    return this.leftDatas.filter(d => d.notMine !== '1' && ((d.groupName.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1) 
    || (d.creator.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1)));
  }
  @computed get shareGroupTypes() {
    return this.leftDatas.filter(d => d.notMine === '1' && ((d.groupName.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1)
    || (d.creator.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1)));
  }
  @computed get shareDeleteDisabled() {
    return this.shareListTableStore.selectedRowKeys.slice().length === 0;
  }
  @action saveTask = () => {
    this.newTaskFrom.validateForm().then(f => {
      if (!f.isValid) {
        f.showErrors();
        return;
      }
      this.newTaskSubmiting = true;
      const formdata = this.newTaskFrom.getFormParams();
      TASKAPI.saveTask(formdata).then((result) => {
        this.newTaskSubmiting = false;
        this.hideNewTaskDialog();
        if (result) {
          if (!result.hasExcel) {
            message.error("新建任务失败,该应用未创建表格");
          }
        } else {
          message.success(getLabel('505987', '新建任务成功'));
        }
      });

    });
  }

  @action deleteGroupApp = () => {

  }

  @action saveGroupApp = () => {
    this.appGroupFrom.validateForm().then(f => {
      if (!f.isValid) {
        f.showErrors();
        return;
      }
      this.newTaskSubmiting = true;
      const formdata = this.appGroupFrom.getFormParams();
      TASKAPI.saveAppGroup(formdata).then((result) => {
        this.newTaskSubmiting = false;
        this.hideNewAppGroupDialog();
        if (result) {
          if (result.error) {
            message.error(result.error);
          } else {
            if (formdata.id) {

              message.success('修改分组名称成功');
            } else {

              message.success('新建分组成功');
            }
          }
          if (result.groupList) {
            this.setLeftData(result.groupList);
          }

        }
      });

    });
  }

  @action deleteAppGroup = (menu) => {
    Modal.confirm({
      title: '删除分组',
      content: '确认要删除该分组？',
      onOk: () => {
        TASKAPI.deleteAppGroup({ id: menu.id })
          .then((result) => {
            if (result) {
              if (result.error) {
                message.error(result.error);
              } else {
                message.success('删除分组成功');
                if (menu.id == this.selectedGroupType) {

                  if (result.groupList && result.groupList.length > 0) {
                    this.changeSelectedGroupType(result.groupList[0].id);
                  } else {

                    this.changeSelectedGroupType(this.firstGroup);
                  }

                }
              }
              if (result.groupList) {
                this.setLeftData(result.groupList);
              }

            }
          }
          );
      }
    });
  }

  @action onNewTask = (app) => {
    this.showNewTaskDialog(app);
  }

  @action checkCreateMaxNum = () => {
    _action.checkCreateMaxNum().then((res) => {
        if(res) {
          const canCreateApp = res.canCreateApp;
          if(canCreateApp) {
            this.canCreated = true;
          } else {
            this.canCreated = false;
          }
        }
    })
  }
  @action hideShareDialog = () => {
    this.shareDialogVisible = false;
  }
  @action saveShareApp = (share) => {
    _action.share({ appid: this.shareApp.id, ...share }).then(() => {
      message.success('共享成功');
      this.hideShareDialog();
      this.reloadTable();
    });
  }
  @action showShareDialog = (app) => {
    this.shareApp = app;
    this.shareListVisible = true;
    shareList(this.shareApp.id).then(data => {
      this.shareListTableStore.getDatas(data.datas);
    });
  }
  @action addShare = () => {
    this.shareDialogVisible = true;
  }
  @action deleteShare = () => {
    const _this = this;
    Modal.confirm({
      content: getLabel('505984', '是否确认删除？'),
      onOk() {
        deleteShare(_this.shareListTableStore.selectedRowKeys.slice().join(','), _this.shareApp.id).then(() => {
          _this.reloadTable();
          message.success(getLabel('505985', '删除成功'));
        });
      },
      onCancel() { },
    });
  }
  @action hideShareList = () => {
    this.shareApp = {};
    this.shareDialogVisible = false;
    this.shareListVisible = false;
  }
  @action changeShareListType = (key) => {
    this.shareListType = key;
  }
  @action reloadTable = () => {
    this.shareListTableStore.reloadCurrent();
  }
  @action onCheck = (checked, app) => {
    const appid = app.id;

    if (checked) {
      this.appids.push(appid);
    } else {
      const index = this.appids.findIndex(id => id === appid);

      this.appids.splice(index, 1);
    }
  }
  @action deleteSingle = (app) => {
    return _action.delete(app.id).then((res) => {
      this.getApps();
      if (res) {
        this.setLeftData(res);
      }
    });
  }
  @action onDelete = () => {
    const ids = this.appids.join(',');
    this.onStatusChange(DELETE);
    return _action.delete(ids).then((data) => {
      this.getApps();
      if (data) {
        this.setLeftData(data);
      }
      this.appids = [];
      this.status = UNKNOWN;
      // return Modal.success({
      //   content: '本次共操作了'+data.count+'条数据，'+data.delCount+'条删除成功，'+data.noRight+'条无删除权限。',
      // });
    });
  }

  @action showPublishDialog = app => {
    this.publishApp = app;
    this.publishDialogVisible = true;
  }

  @action hidePublishDialog = app => {
    this.publishApp = {};
    this.publishDialogVisible = false;
  }

  @action showNewTaskDialog = (app) => {
    createDay();
    this.newTaskSubmiting = false;
    this.newTaskFrom.setCondition(createCondition(true, 0));
    this.newTaskFrom.updateFields({
      appid: { value: app.id },
      appName: { value: app.name },
      name: { value: '' },
      cycle: { value: '0' }
    });
    this.baseDateHide = true;
    this.newTaskDialogVisible = true;
    this.newTaskApp = app;
  }

  @action updateCondition = (bool, cycle) => {
    this.baseDateHide = bool;
    this.newTaskFrom.setCondition(createCondition(bool, cycle));
    this.newTaskFrom.updateFields({
      cycle: { value: cycle }
    });
  }

  @action hideNewTaskDialog = () => {
    this.newTaskDialogVisible = false;
    this.newTaskApp = {};
  }

  @action hideNewAppGroupDialog = () => {
    this.newAppGroupDialogVisible = false;
    this.newAppGroup = {};
  }

  @action init = () => {
    this.loading = true;
    Promise.all([
      this.getLeftDatas()
    ]).then(() => {
      this.loading = false;
    });
  }

  @action
  changeSelectedGroupType = (selectedGroupType) => {
    this.checkIsMine(selectedGroupType);
    this.searchText = '';
    this.selectedGroupType = selectedGroupType;
    this.current = 1
    this.getApps();
  }


  @action
  checkIsMine = (selectedGroupType) => {
    this.notMine =  ((this.leftDatas.filter( d => d.id == selectedGroupType)[0]) || {}).notMine;
  }

  @action getAppPathid = (app) => {
    TASKAPI.getAppPathid({
      "appid": app.id
    }).then((value) => {
      if (value) {
        this.onNewTask(app);
      } else {
        message.error(getLabel('505956', '未设置路径，请先设置路径'));
      }
    })
  }

  @action changePage = (page) => {
    this.appids = [];
    this.current = page;
    this.tableStore.getDatas(this.sessionkey, page, this.pageSize);
  }
  @action changePageSize = (current, pageSize) => {
    this.current = 1;
    this.pageSize = pageSize;
    this.tableStore.getDatas(this.sessionkey, this.current, pageSize);
  }

  @computed get apps() {
    return this.tableStore.datas;
  }

  @computed get total() {
    return this.tableStore.count;
  }

  getApps() {
    this.spinning = true;
    const selectedType = this.selectedType;
    const searchText = this.searchText;
    this.appids = [];
    return _action.getApps({ selectedType, searchText, groupid: this.selectedGroupType }).then(result => {
      this.sessionkey = result.sessionkey.datas;
      this.tableStore.getDatas(this.sessionkey, this.current, this.pageSize);

      //判断创建权限、维护权限
      this.createRight = result.createRight;
      this.modifyRight = result.modifyRight;
      // 是否达到最大创建数（false为已达上限，不能再创建）
      this.canCreated = result.canCreated;

      console.log(this.canCreated);
      this.counts = {
        [ALL]: result.allLen,
        [FREE]: result.freeLen,
        [MULTI]: result.multiLen
      };
      this.spinning = false;
    });
  }

  @action getLeftDatas = () => {
    _action.getLeftDatas().then((data) => {
      this.setLeftData(data);
      this.getApps();
    });
      
  }
  @action
  setLeftData = (data) => {
    this.leftDatas = data;
    if(data.length > 0) {
      this.firstGroup = data[0].id + '';
      if(this.selectedGroupType == '-2') 
        this.selectedGroupType = this.firstGroup;
      
    }
    
  }

  @action onSelectedTypeChange = selectedType => {
    this.selectedType = selectedType;
    this.current = 1
    this.getApps();
  }

  @action onSearchTextChange = searchText => {
    this.searchText = searchText;
    this.current = 1
    this.getApps();
  }

  @action onStatusChange = status => {
    this.status = status;
  }

  @action onTypesChange = types => {
    types = types.map(({ name, face }) => {
      return {
        key: name,
        title: face,
        showcount: true
      }
    });

    types.unshift({ key: ALL, title: getLabel('507383', '全部'), showcount: true });

    this.types = types;
  }

  @action onEditableAppChange = (editableApp = {}) => {
    this.editableApp = editableApp;
  }

  @action hideDialog = () => {
    this.onStatusChange(UNKNOWN);
    this.onEditableAppChange();
  }

  @action showNewDialog = () => {
    this.onStatusChange(NEW);
    
    this.checkCreateMaxNum();
  }

  @action showEditDialog = app => {
    this.onStatusChange(EDIT);
    this.onEditableAppChange(app);
  }

  @action onNewOrEdit = (app, hasNotModify) => {
    if (hasNotModify) return this.hideDialog();

    const isEdit = !!app.id;
    const method = isEdit ? 'edit' : 'create';
    _action[method](app).then((res) => {
      this.hideDialog();
      this.getApps();
      if (res) {
        this.setLeftData(res);
      }
    });
  }

  showDesigner = (app) => {
    window.open(`${DESIGN_URL}#/${route.designer}/${app.id}`);
  }
  showData = (app) => {
    window.open(`${DESIGN_URL}#/${route.data}?appid=${app.id}`);
  }

  @action setLeftSearchValue = (value) => {
    this.searchValue = value;
  }

  @action showAppGroupDialog = (app) => {
    this.newTaskSubmiting = false;
    this.appGroupFrom.setCondition([{
      items: [{
        conditionType: INPUT,
        domkey: ["id"],
        label: 'id',
        hide: true
      }, {
        conditionType: INPUT,
        domkey: ["groupName"],
        rules: 'required',
        label: '名称',
        viewAttr: 3
      }],
      defaultshow: true
    }]);
    this.appGroupFrom.updateFields({
      groupName: { value: (app || {}).groupName || "" },
      id: { value: (app || {}).id || "" }
    });
    this.newAppGroupDialogVisible = true;
    this.newAppGroup = app;
  }
}